package com.itlong.cloud.smartcard.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.ProjectSmartCommunityStatusChangeDTO;
import com.itlong.cloud.POJO.DTO.property.HouseHoldManageJPushDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardGetAppUserInfoDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardSyncDataPullUserBasisInfoDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardSyncDataTmpAuthDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.property.AppUserGetDeviceAuthVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppPadFaceDao;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.property.dao.IPropertyAppUserInfoDao;
import com.itlong.cloud.property.dao.IPropertyAppUserProjectDao;
import com.itlong.cloud.property.service.IPropertyHouseHoldInfoService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.smartcard.dao.ISmartCardOldUserInfoDao;
import com.itlong.cloud.smartcard.dao.ISmartCardUserInfoDao;
import com.itlong.cloud.smartcard.service.ISmartCardUserInfoService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * <desc>
 *       一卡通—用户模块服务接口实现类。
 * <desc/>
 *
 * @createDate 2017/11/1.
 */
@Service
public class SmartCardUserInfoServiceImpl implements ISmartCardUserInfoService {

    private static final Logger LOG = LoggerFactory.getLogger(SmartCardUserInfoServiceImpl.class);

    // 旧一卡通_用户模块操作数据库接口
    @Autowired
    ISmartCardOldUserInfoDao iSmartCardOldUserInfoDao;
    //App用户信息数据库访问对象
    @Autowired
    private IPropertyAppUserInfoDao iPropertyAppUserInfoDao;

    //一卡通App用户信息数据库访问对象
    @Autowired
    private ISmartCardUserInfoDao iSmartCardUserInfoDao;

    //App用户项目信息数据库访问对象
    @Autowired
    private IPropertyAppUserProjectDao iPropertyAppUserProjectDao;

    @Autowired
    private IPropertyHouseHoldInfoService iPropertyHouseHoldInfoService;

    @Autowired
    IAppPadFaceDao iAppPadFaceDao;


    //Redis工具接口类
    @Autowired
    private RedisService<PropertyUserCacheVO> redisService;


    @Autowired
    private MessageSender messageSender;
    /**
     * <desc>
     * 保存或更新住户信息以及住户项目信息
     * <desc/>
     *
     * @param smartCardSyncDataPullUserBasisInfoDTO 住户信息传输对象
     * @param projectId                             项目Id
     * @param isSmartCommunity                      是否使用云对讲： 0-否，1-是
     * @return
     * @author zhangs
     * @createDate 2017-11-20
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void saveOrUpdateSmartCardUserBasisInfo(SmartCardSyncDataPullUserBasisInfoDTO smartCardSyncDataPullUserBasisInfoDTO,
                                                   String projectId, Integer isSmartCommunity) throws Exception {
        String phoneNum = smartCardSyncDataPullUserBasisInfoDTO.getUserPhone();
        String email = smartCardSyncDataPullUserBasisInfoDTO.getUserEmail();
        //将用户基本信息更新到数据库（事务保护）
        String userIdWhenProjectStatusChanged = saveOrUpdateSmartCardUserBasisInfoToDB(smartCardSyncDataPullUserBasisInfoDTO,projectId,isSmartCommunity);
        if (StringUtils.isNotBlank(userIdWhenProjectStatusChanged)){
            this.notifyMsgWhenSmartCardUserProjectStatusChange(userIdWhenProjectStatusChanged,phoneNum,email,projectId,isSmartCommunity);
        }

    }


    /**
     * <desc>
     *     保存或更新住户信息以及住户项目信息到数据库
     * <desc/>
     *
     * @param smartCardSyncDataPullUserBasisInfoDTO 住户信息传输对象
     * @param projectId                             项目Id
     * @param isSmartCommunity                      是否使用云对讲： 0-否，1-是
     * @return 用户项目状态时返回用户ID，否则返回空字符串
     * @author LewisLouis
     * @createDate 2018-02-26
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public String saveOrUpdateSmartCardUserBasisInfoToDB(SmartCardSyncDataPullUserBasisInfoDTO smartCardSyncDataPullUserBasisInfoDTO,
                                                   String projectId, Integer isSmartCommunity) throws Exception{
        String userIdWhenProjectStatusChanged = "";
        String phoneNum = smartCardSyncDataPullUserBasisInfoDTO.getUserPhone();
        String email = smartCardSyncDataPullUserBasisInfoDTO.getUserEmail();
        //判断住户信息是否已存在
        SmartCardGetAppUserInfoDTO getAppUserInfoDTO = new SmartCardGetAppUserInfoDTO();
        getAppUserInfoDTO.setProjectId(projectId);
        getAppUserInfoDTO.setPhoneNum(phoneNum);
        getAppUserInfoDTO.setEmail(email);
        AppUserInfoPO appUserInfoPO = this.getSmartCardAppUserInfo(getAppUserInfoDTO);
        String userId;
        String userProjectStastus =  String.valueOf(smartCardSyncDataPullUserBasisInfoDTO.getUserStatus());
        Date date = new Date();
        if (appUserInfoPO != null) {
            //已存在
            userId = appUserInfoPO.getUserId();
            appUserInfoPO.setRealName(smartCardSyncDataPullUserBasisInfoDTO.getUserName());
            appUserInfoPO.setUpdateTime(date);
            appUserInfoPO.setPhoneNum(phoneNum);
            appUserInfoPO.setEmail(email);
            iPropertyAppUserInfoDao.update(appUserInfoPO);
        } else {
            //不存在
            appUserInfoPO = new AppUserInfoPO();
            userId = LogicIdUtil.userBusinessId();
            appUserInfoPO.setUserId(userId);
            appUserInfoPO.setPhoneNum(phoneNum);
            appUserInfoPO.setEmail(email);
            appUserInfoPO.setRealName(smartCardSyncDataPullUserBasisInfoDTO.getUserName());
            appUserInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            appUserInfoPO.setUpdateTime(date);
            appUserInfoPO.setCreateTime(date);
            iPropertyAppUserInfoDao.save(SqlUtil.durableData(appUserInfoPO, PlatformConstants.TABLE_SAVE));
        }

        //判断住户项目信息是否已存在
        AppUserProjectPO appUserProjectPO = new AppUserProjectPO();
        appUserProjectPO.setProjectId(projectId);
        appUserProjectPO.setUserId(userId);
        appUserProjectPO.setCardNum(smartCardSyncDataPullUserBasisInfoDTO.getCardNum());
        appUserProjectPO.setUserType(AppUserProjectUserTypeEnum.USERPROJECT_USERTYPE_ORDINARY.getType());
        appUserProjectPO.setStatus(null); //查询所有状态的
        List<AppUserProjectPO> appUserProjectPOS = iPropertyAppUserProjectDao.getUserProject(appUserProjectPO);
        if ((null == appUserProjectPOS) || (appUserProjectPOS.isEmpty())) {
            appUserProjectPO.setUserProjectStatus(userProjectStastus);
            appUserProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
            appUserProjectPO.setUpdateTime(date);
            appUserProjectPO.setCreateTime(date);
            appUserProjectPO.setCardNum(appUserProjectPO.getCardNum());
            //LOG.info(String.format("根据一卡通同步到云端的数据保存了用户-项目信息:%s",JSON.toJSONString(appUserProjectPO)));
            iPropertyAppUserProjectDao.save(SqlUtil.durableData(appUserProjectPO, PlatformConstants.TABLE_SAVE));
            //住户项目信息不存在则需新增SIP信息以及同步SIP信息
            if (ProjectSmartCommunityStatusEnum.PROJECT_SMART_COMMUNITY_YES.getType() == isSmartCommunity) {
                ProjectSmartCommunityStatusChangeDTO sipChangeDTO = new ProjectSmartCommunityStatusChangeDTO();
                sipChangeDTO.setIsSmartCommunity(isSmartCommunity);
                sipChangeDTO.setProjectId(projectId);
                sipChangeDTO.setUserId(userId);
                iPropertyHouseHoldInfoService.updateUserProjectSip(sipChangeDTO);
            }
        } else {
            //已存在
            AppUserProjectPO appUserProject = appUserProjectPOS.get(0);
            String oldUserProjectStatus = appUserProject.getUserProjectStatus();
            appUserProject.setUserProjectStatus(userProjectStastus);
            appUserProject.setStatus(DataStatusEnum.NORMAL.getType());
            appUserProject.setCardNum(smartCardSyncDataPullUserBasisInfoDTO.getCardNum());
            appUserProject.setUpdateTime(date);
            if (appUserProject.getUserType() == null) {
                appUserProject.setUserType(AppUserProjectUserTypeEnum.USERPROJECT_USERTYPE_ORDINARY.getType());
            }
            iPropertyAppUserProjectDao.update(appUserProject);
            //LOG.info(String.format("根据一卡通同步到云端的数据更新了用户-项目信息:%s",JSON.toJSONString(appUserProjectPO)));
            if(!StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(oldUserProjectStatus,userProjectStastus)){
                userIdWhenProjectStatusChanged = userId;
            }

             //   this.notifyMsgWhenSmartCardUserProjectStatusChange(userId,phoneNum,email,projectId,isSmartCommunity);

        }

        return userIdWhenProjectStatusChanged;
    }


    /**
    * <desc>
    *     一卡通用户状态变更，通知其它各模块.
    * </desc>
    *
     *@param userId 用户Id
    * @param userPhone 用户手机号
     *@param projectId 项目Id
     * @param isSmartCommunity 项目是否启用云对讲
    * @return xx
    * @author LewisLouis
    * @createDate 2018-01-04
    */
    private void notifyMsgWhenSmartCardUserProjectStatusChange(String userId,String userPhone,String userEmail,
                                                               String projectId,Integer isSmartCommunity) throws Exception{
        //若用户已在app端注册
        if (NumberHandlerUtil.isGreaterThan(iSmartCardOldUserInfoDao.checkPhone(userPhone), 0)){
            //1.刷新权限变更
            sendMessageForUserAuthChanged(userId,projectId);

            //2.若项目启用云对讲则需推送云对讲指令
            if (ProjectSmartCommunityStatusEnum.PROJECT_SMART_COMMUNITY_YES.getType().equals(isSmartCommunity)){
                List<DeviceBusinessChangeLogPO> changeLogPOS = new ArrayList<>();
                JSONObject json = new JSONObject();
                json.put("userId", userId);
                json.put("projectId", projectId);
                DeviceBusinessChangeLogPO deviceBusinessChangeLogPO =
                        new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_USER_PROJECT, json,projectId);
                changeLogPOS.add(deviceBusinessChangeLogPO);
                JSONObject dataJs = new JSONObject();
                dataJs.put("data",changeLogPOS);
                messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                        JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);

                //云电梯
                DeviceBusinessElevatorChangeLogPO deviceBusinessElevatorChangeLogPO
                        = new DeviceBusinessElevatorChangeLogPO(projectId,
                        CloudElevatorChangeBusinessEnum.PUSH_USER_PROJECT,json.toJSONString());
                List<DeviceBusinessElevatorChangeLogPO> deviceElevatorChangeLogPOS = new ArrayList<>();
                deviceElevatorChangeLogPOS.add(deviceBusinessElevatorChangeLogPO);
                dataJs.put("data",deviceElevatorChangeLogPOS);
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE,
                        JsonUtil.toJSON(dataJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_ROUTING_KEY);

                // 云门禁
                List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
                changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_USER_PROJECT, json, projectId));
                dataJs.put("data", changeEntranceLogPOS);
                //发送云门禁指令
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                        JSON.toJSONString(dataJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
                );
            }
            //3.极光推送用户状态变更推送指令
            Map<String,String> comands = new HashMap<>();
            comands.put("refreshSips", "1");
            //推送消息
            String msg = "您的住户权限状态已发生变化";
            List<HouseHoldManageJPushDTO> houseHoldManageJPushDTOS = new ArrayList<>();
            HouseHoldManageJPushDTO houseHoldManageJPushDTO = new HouseHoldManageJPushDTO();
            houseHoldManageJPushDTO.setMsg(msg);
            houseHoldManageJPushDTO.setPhoneNum(userPhone);
            houseHoldManageJPushDTO.setEmail(userEmail);
            houseHoldManageJPushDTO.setProjectId(projectId);
            houseHoldManageJPushDTO.setComands(comands);
            houseHoldManageJPushDTOS.add(houseHoldManageJPushDTO);
            JSONObject dataJs = new JSONObject();
            dataJs.put("data", JSONObject.toJSON(houseHoldManageJPushDTOS));
            messageSender.send(RabbitMQConstant.RABBITMQ_HOUSEHOLD_JPUSH_QUEUE,
                    JSON.toJSONString(dataJs), RabbitMQConstant.RABBITMQ_HOUSEHOLD_JPUSH_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_HOUSEHOLD_JPUSH_KEY);
        }
    }

    /**
     * <desc>
     *      一卡通用户权限变更时发送通知消息
     * <desc/>
     *
     * @param
     * @return
     * @author Chunjian.G
     * @createDate 2017-12-18
     */
    private void sendMessageForUserAuthChanged(String userId, String projectId) throws Exception {
        //住户设备权限更新时通知后台移动App模块
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("projectId", projectId);
        messageSender.send(RabbitMQConstant.RABBITMQ_EQUIP_APP_USER_INFO_DEVICE_UPDATE_QUEUE,
                JSON.toJSONString(param), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                RabbitMQConstant.RABBITMQ_EQUIP_APP_USER_INFO_DEVICE_UPDATE_KEY);

        //住户设备权限更新时通知后台移动App模块更新用户二维码
//        messageSender.send(RabbitMQConstant.RABBITMQ_EQUIP_APP_USER_QRCODE_UPDATE_QUEUE,
//                JSON.toJSONString(param), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
//                RabbitMQConstant.RABBITMQ_EQUIP_APP_USER_QRCODE_UPDATE_KEY);
        //LOG.info(String.format("一卡通用户权限变更通知更新权限及二维码：projectId-%s，userId-%s", projectId, userId));
    }

    /**
     * <desc>
     *     根据住户手机号或邮箱获取住户信息
     * <desc/>
     *
     * @param getAppUserInfoDTO 查询条件
     * @return AppUserInfoPO 住户信息
     * @author zhangs
     * @createDate 2017/11/20
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public AppUserInfoPO getSmartCardAppUserInfo(SmartCardGetAppUserInfoDTO getAppUserInfoDTO) {
        AppUserInfoPO appUserInfo = null;
        if (StringUtils.isNotBlank(getAppUserInfoDTO.getPhoneNum())){
            appUserInfo =  this.getSmartCardAppUserInfoByPhoneNo(getAppUserInfoDTO.getProjectId(),getAppUserInfoDTO.getPhoneNum());
        }
        if ((null == appUserInfo) && (StringUtils.isNotBlank(getAppUserInfoDTO.getEmail()))){
            appUserInfo =  this.getSmartCardAppUserInfoByEmail(getAppUserInfoDTO.getProjectId(),getAppUserInfoDTO.getEmail());
        }
        return appUserInfo;
    }

    /**
     * <desc>
     *    根据住户手机号获取住户信息
     * <desc/>
     *
     * @param projectId 项目Id
     * @param phoneNum  App用户手机号
     * @return AppUserInfoPO 住户信息
     * @author zhangs
     * @createDate 2017/11/20
     */
    private AppUserInfoPO getSmartCardAppUserInfoByPhoneNo(String projectId, String phoneNum) {
        Map<String, Object> params = new HashMap<>();
        params.put("phoneNum", phoneNum);
        List<AppUserInfoPO> appUserInfoPOS = iSmartCardUserInfoDao.getSmartCardAppUserInfo(params);
        if (appUserInfoPOS.isEmpty()) {
            return null;
        } else {
            return appUserInfoPOS.get(0);
        }
    }

    /**
     * <desc>
     *    根据住户邮箱获取住户信息
     * <desc/>
     *
     * @param projectId 项目Id
     * @param email  App用户邮箱
     * @return AppUserInfoPO 住户信息
     * @author zhangs
     * @createDate 2017/11/20
     */
    private AppUserInfoPO getSmartCardAppUserInfoByEmail(String projectId, String email) {
        Map<String, Object> params = new HashMap<>();
        params.put("email", email);
        List<AppUserInfoPO> appUserInfoPOS = iSmartCardUserInfoDao.getSmartCardAppUserInfo(params);
        if (appUserInfoPOS.isEmpty()) {
            return null;
        } else {
            return appUserInfoPOS.get(0);
        }
    }

    /**
     * <desc>
     * 与旺龙一卡通对接-处理住户设备权限信息。
     * 一卡通push住户设备权限信息时住户信息为空，先存储住户信息在使用RabbitMQ处理住户设备权限信息
     * <desc/>
     *
     * @param phoneNum                住户手机号
     * @param email  住户邮箱
     * @param projectId               项目Id
     * @param isSmartCommunity        是否使用云对讲： 0-否，1-是
     * @param appUserGetDeviceAuthVOS 住户设备权限数据信息
     * @return
     * @author zhangs
     * @createDate 2017/11/20
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void handleSmartCardPushDeviceAuth(String phoneNum,
                                              String email,
                                              String projectId, Integer isSmartCommunity, List<AppUserGetDeviceAuthVO> appUserGetDeviceAuthVOS) throws Exception {
        System.out.println(String.format("开始处理：%s %s %s的用户权限信息",phoneNum,email,projectId));
        String userId = LogicIdUtil.userBusinessId();

        //保存用户信息到数据库（事务保护）
        this.handleSmartCardPushDeviceAuthToDB(userId,phoneNum,email,projectId,isSmartCommunity,appUserGetDeviceAuthVOS);



        SmartCardSyncDataTmpAuthDTO smartCardSyncDataTmpAuthDTO = new SmartCardSyncDataTmpAuthDTO();
        smartCardSyncDataTmpAuthDTO.setUserId(userId);
        smartCardSyncDataTmpAuthDTO.setAppUserGetDeviceAuthVOS(appUserGetDeviceAuthVOS);
       // try {
            //rabbitmq 发送任务
            //LOG.info("RabbitMQ_与旺龙一卡通对接-处理住户设备权限信息_生产者:" + JSON.toJSONString(smartCardSyncDataTmpAuthDTO));
            JSONObject dataJs = new JSONObject();
            dataJs.put("data", JSONObject.toJSON(smartCardSyncDataTmpAuthDTO));
            messageSender.send(RabbitMQConstant.RABBITMQ_DOCKWITHSMARTCARD_HANDLE_DEVICEAUTH_QUEUE,
                    JSON.toJSONString(dataJs), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_DOCKWITHSMARTCARD_HANDLE_DEVICEAUTH_ROUTING_KEY);
       // } catch (Exception e) {
            //回滚当前事务
           // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      //  }
        System.out.println(String.format("结束处理：%s %s %s的用户权限信息",phoneNum,email,projectId));
    }

    /**
     * <desc>
     *    与旺龙一卡通对接-处理住户设备权限信息。
     *    一卡通push住户设备权限信息时住户信息为空，先存储住户信息到数据库
     * <desc/>
     *
     * @param phoneNum                住户手机号
     * @param email  住户邮箱
     * @param projectId               项目Id
     * @param isSmartCommunity        是否使用云对讲： 0-否，1-是
     * @param appUserGetDeviceAuthVOS 住户设备权限数据信息
     * @return
     * @author LewisLouis
     * @createDate 2018-02-26
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void handleSmartCardPushDeviceAuthToDB(String userId,String phoneNum,
                                              String email,
                                              String projectId, Integer isSmartCommunity, List<AppUserGetDeviceAuthVO> appUserGetDeviceAuthVOS) throws Exception {

        Date date = new Date();
       // String userId = LogicIdUtil.userBusinessId();
        //保存住户信息
        AppUserInfoPO appUserInfo = new AppUserInfoPO();
        appUserInfo.setUserId(userId);
        appUserInfo.setPhoneNum(phoneNum);
        appUserInfo.setEmail(email);
        appUserInfo.setStatus(DataStatusEnum.NORMAL.getType());
        appUserInfo.setCreateTime(date);
        appUserInfo.setUpdateTime(date);
        iPropertyAppUserInfoDao.save(SqlUtil.durableData(appUserInfo, PlatformConstants.TABLE_SAVE));
        //保存住户项目信息
        AppUserProjectPO appUserProjectPO = new AppUserProjectPO();
        appUserProjectPO.setUserId(userId);
        appUserProjectPO.setProjectId(projectId);
        appUserProjectPO.setUserProjectStatus(String.valueOf(AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_ENABLE.getType()));
        appUserProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
        appUserProjectPO.setUserType(AppUserProjectUserTypeEnum.USERPROJECT_USERTYPE_ORDINARY.getType());
        appUserProjectPO.setCreateTime(date);
        appUserProjectPO.setUpdateTime(date);
        //住户项目信息不存在时需新增SIP信息同时同步SIP信息
        if (ProjectSmartCommunityStatusEnum.PROJECT_SMART_COMMUNITY_YES.getType() == isSmartCommunity) {
            StringBuffer sipAccount = new StringBuffer(projectId + phoneNum);
            StringBuffer sipPsd = new StringBuffer(phoneNum + userId + projectId);
            appUserProjectPO.setSipAccount(sipAccount.toString());
            appUserProjectPO.setSipPsd(Md5EncryptUtil.md5(sipPsd.toString()).toLowerCase());
            //删除原SIP相关信息,并添加/更新SIP信息
            iPropertyHouseHoldInfoService.cloudSipHandler(projectId,sipAccount.toString(), appUserProjectPO.getSipPsd(), null);
        }
        iPropertyAppUserProjectDao.save(SqlUtil.durableData(appUserProjectPO, PlatformConstants.TABLE_SAVE));

    }

    /**
     * <desc>
     *      C#端管理中心登陆验证（工程人员）。
     * <desc/>
     *
     * @param projectId 项目编号
     * @param userName 账号
     * @param password 密码
     * @return
     * @author Juguang.S
     * @createDate 2019-03-18
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Map<String, String> engineerLoginVerifyForCFace(String projectId, String userName, String password) throws Exception {
        if(iAppPadFaceDao.engineerLoginVerify(projectId,userName,password)>0){
            //登录成功则生成token 及查询项目下配置人脸权限增量同步时长
            String userId = iAppPadFaceDao.getUserIdByUserName(userName);
            String token = UserTokenUtil.tokenEncrypt(userId,PlatformConstants.C_MANAGEMENT_USER_TOKEN_KEY, SystemTypeEnum.SMART_CARD.getType());
            String cacheKey = String.format("%s%s", RedisConstant.MANAGEMENT_USER_REDIS_KEY, userId);
            redisService.set(cacheKey, RedisConstant.SDKSERVER_LOGIN_TIME, token);
            //此处待查询项目下配置人脸权限增量同步时长字段
            Integer systemDataTime = iAppPadFaceDao.getSystemDataTimeByProjectId(projectId);
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("token",token);
            resultMap.put("systemDataTime",systemDataTime+"");
            return resultMap;
        }
        return null;
    }

    /**
     * <desc>
     *      从缓存中获取token信息
     * </desc>
     *
     * @param token 用户token
     * @return
     * @author Juguang.S
     * @createDate 2019/03/18
     */
    @Override
    public String retrieve(String token) {
        String userId = UserTokenUtil.tokenDecrypt(token, PlatformConstants.C_MANAGEMENT_USER_TOKEN_KEY);
        String cacheKey = String.format("%s%s", RedisConstant.MANAGEMENT_USER_REDIS_KEY, userId);
        return redisService.get(cacheKey);
    }

    /**
     * <desc>
     *      获取用户信息
     * </desc>
     *
     * @param uid
     * @param projectId
     * @return
     * @author Jiaqi.X
     * @createDate 2019/11/18
     */
    public String getUserIdByUid(String uid,String projectId){
        return iSmartCardUserInfoDao.getUserIdByUid(uid,projectId);
    }

    /**
     * <desc>
     *      查询通行记录
     * </desc>
     *
     * @param uid
     * @param projectId
     * @param passTime
     * @return
     * @author Jiaqi.X
     * @createDate 2019/11/18
     */
    public String getPassIdByQrcodeInfo(String uid,String projectId,String passTime){
        return iSmartCardUserInfoDao.getPassIdByQrcodeInfo(uid,projectId,passTime);
    }

    /**
     * <desc>
     *      人脸下发失败回调
     * <desc/>
     *
     * @param projectId 项目编号
     * @param faceFailDesc  下发失败原因描述(中文)
     * @param userId  人脸识别后的faceId
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/12
     */
    @Override
    public void faceFailCallback(String projectId, String faceFailDesc, String userId) throws Exception {
        iSmartCardUserInfoDao.updateAppUserProjectInfo(projectId,faceFailDesc,userId);
    }

    /**
     * <desc>
     *      更新二维码信息
     * </desc>
     *
     * @param visitorId 访客id
     * @return
     * @Author Zhu.yj
     * @createDate  2021/5/31
     */
    @Override
    public String updateQRCode(String visitorId) throws Exception {

        return null;
    }

}
